package cn.elwy.rcp.ui.table.format;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.datatype.XMLGregorianCalendar;

public class DateFormat extends ColumnFormat {

  private static final long serialVersionUID = 1L;

  private static Map<String, SimpleDateFormat> formats = new HashMap<String, SimpleDateFormat>();

  public DateFormat(String pattern) {
    super(pattern);
  }

  @Override
  public String format(Object value) {
    if (value == null) {
      return "";
    }
    try {
      if (value instanceof XMLGregorianCalendar) {
        value = convertToDate((XMLGregorianCalendar) value);
      }
      SimpleDateFormat format = getFormat();
      return format.format(value);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return value.toString();
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> T parse(String value, Class<T> clazz) {
    SimpleDateFormat format = getFormat();
    try {
      return (T) format.parse(value);
    } catch (ParseException e) {
      e.printStackTrace();
      return null;
    }
  }

  public SimpleDateFormat getFormat() {
    SimpleDateFormat format = formats.get(getPattern());
    if (format == null) {
      format = new SimpleDateFormat(getPattern());
      formats.put(getPattern(), format);
    }
    return format;
  }

  private Date convertToDate(XMLGregorianCalendar calendar) {
    try {
      return calendar.toGregorianCalendar().getTime();
    } catch (Exception e) {
      return null;
    }
  }

}
